﻿/////////////////////////////////////////////页面事件//////////////////////////////////////
// 保存标题事件
$("#TitleSave").click(function () {
    page.TitleSave();
});

// 保存轮播图/单图事件
$("#LunBoTuSave").click(function () {
    page.LunBoTuSave();
});

// 保存背景图事件
$("#BackgroundImgSave").click(function () {
    page.BackGroundImgSave();
});

//富文本保存事件
$("#RichTextSave").click(function () {
    page.RichTextSave();
})

////////////////////////////////////////////////////////////////////////////////////////////////
// 按钮管理--添加按钮
$("#AddButton").click(function () {
    var buttonId = 0;
    Button.EditModelDialog(buttonId);
});

////////////////////////////////////////////////////////////////////////////////////////

function ShowIcon(e) {
    $(".rightForm").hide();
    $("#ButtonListWrap").show();
    if (e && e.stopPropagation) {
        e.stopPropagation()
    } else {
        window.event.cancelBubble = true;
    }
}



//拖拽图对象
var DragImg = [];

$.extend(DragImg, {

    BindDragImg: function () {

        var d = $("#DragImgIsHidden").val();
        $("input[name='AntiFakeDragInp'][value=" + d + "]").attr("checked", true);

    }

});


///轮播图对象
var CarouselFigure = [];


$.extend(CarouselFigure, {

    AppendImg: function (imgObj) {

        var htmlRight = ['<div class="upload_warp_img_div" id="WU_FILE_0">',
            '<div class="upload_warp_img_div_top">',
            '<img src="/Content/webImgs/AntiFakePage/del.png" class="upload_warp_img_div_del" onclick="delSwpierImg(this)">',
            '</div><div class="upload_warp_img_div_text">',
            '<img alt="null" class="uploadImg" src="' + imgObj + '">',
            '</div>',
            '</div>'].join("");
        $("#LbtList").append(htmlRight);

        var HtmlLbt = ['<img class="swiper-slide addSwpierImg swiper-slide-active" src="' + imgObj + '" style="width: 324px;">'].join("");
        $("#_top_img").append(HtmlLbt);


    },


    BindList: function () {
        var lbtJson = $("#LbtJson").val();
        if (lbtJson != "") {

            var array = JSON.parse(lbtJson);
            for (var i = 0; i < array.length; i++) {

                CarouselFigure.AppendImg(array[i]);
            }
            ShowDefaultImg($(".upload_warp_img_div").length)
        }
    },


});


var Button = []
$.extend(Button, {
    GetList: function (moduleId) {
        $.ajax({
            url: "/AntiFake/GetButtonList",
            type: "Post",
            data: { moduleId: moduleId },
            success: function (data) {
                var result = data;
                var html = "";
                var iconHtml = "";
                if (result.length == 0) {
                    iconHtml = ['<div class="IconBox">',
                                    '<img src="' + defaultIconSrc + '" />',
                                    '<span style="white-space:nowrap;">防伪</span>',
                                '</div>',
                                '<div class="IconBox">',
                                    '<img src="' + defaultIconSrc + '" />',
                                    '<span style="white-space:nowrap;">溯源</span>',
                                '</div>'].join("")
                } else {
                    for (var i = 0; i < result.length; i++) {
                        html += ['<li class="row">',
                                    '<div class="col-sm-4 border">',
                                        '<img src="' + result[i].IcoUrl + '" />',
                                        '<span style="margin-left:10px">' + result[i].Name + '</span>',
                                    '</div>',
                                    '<button data-id="' + result[i].ButtonId + '" class="btn btn-primary" onclick="Button.EditModel(this)">修改</button>',
                                    '<button data-id="' + result[i].ButtonId + '" class="btn btn-danger" onclick="Button.DeleteModel(this)">删除</button>',
                                '</li>'].join("")
                     
                        if ($("#TempletId").val() == 2) {
                            iconHtml += ['<div data-id="' + result[i].ButtonId + '" class="IconBox">',
                                            '<img src="' + result[i].IcoUrl + '" />',
                                            '<span style="white-space:nowrap;">' + result[i].Name + '</span>',
                                        '</div>'].join("");
                        } else {
                            iconHtml += ['<div data-id="' + result[i].ButtonId + '" class="IconBox">',
                                            '<img src="' + result[i].IcoUrl + '" />',
                                            '<span style="white-space:nowrap;color:white;">' + result[i].Name + '</span>',
                                         '</div>'].join("");
                        }
                    }
                }
                $("#ButtonList").html(html);
                $("#icon").html(iconHtml)
            },
            error: function () {
                alert("错了")
            }
        });
        return;
    },

    // 认证库
    Dialog_SelectAuthListObj: null,
    Dialog_SelectAuthList: function (_this) {
        this.Dialog_SelectAuthListObj = $.L.dialog({
            url: ACTION_URL("SelectAuthList", "Auth"),
            title: "认证库选择",
            width: 550,
            height: 500,
        });
    },

    SaveModel: function () {
        var data = $("#ButtonForm").serializeObject();
        $.ajax({
            url: "/AntiFake/ButtonSave",
            type: "Post",
            data: data,
            success: function (data) {
                var result = data;
                Button.GetList(moduleId);
            }
        });
    },

    // 添加按钮导航弹出框
    NavEditDialog: null,
    EditModelDialog: function (buttonId) {
        Button.NavEditDialog = $.L.dialog({
            url: ACTION_URL("ButtonEdit", "AntiFake") + "?buttonId=" + buttonId + "&moduleId=" + moduleId,
            title: "导航",
            width: 400,
            height: "auto",
            buttons: {
                "button_save": {
                    type: 'primary',
                    text: '保存',
                    click: function () {
                        Button.SaveModel();
                        Button.NavEditDialog.close();
                    }
                },
                "button_cancel": {
                    type: 'default',
                    text: '取消',
                    click: 'MODALMISS'
                }
            }
        });
    },

    // 按钮管理--修改按钮
    EditModel: function (obj) {
        var buttonId = $(obj).attr("data-id");
        Button.EditModelDialog(buttonId);
    },

    // 按钮管理--删除按钮
    DeleteModel: function (obj) {
        var buttonId = $(obj).attr("data-id");
        $.ajax({
            url: "/AntiFake/ButtonDelete",
            type: "POST",
            data: { buttonId: buttonId },
            success: function (data) {
                var result = data;
                Button.GetList(moduleId);
            }
        });
    },


    BindModelToButtonEdit: function (buttonId) {


        $.ajax({
            url: "/AntiFake/GetButtonById",
            type: "POST",
            data: { buttonId: buttonId },
            success: function (data) {
                var model = data;


                $("#ButtonForm #ButtonId").val(model.ButtonId);
                $("#ButtonForm #Name").val(model.Name);
                $("#ButtonForm #ico").attr("src", model.IcoUrl);
                $("#ButtonForm #IcoUrl").val(model.IcoUrl);

                $("input[name='Link'][value=" + model.Link + "]").attr("checked", true);
                $("#BindValue").val(model.BindValue);

            }


        });


    },

});



$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};







$.MGJ.DiamondEdition = [];
(function () {
    var _this = $.MGJ.DiamondEdition;
    $.extend($.MGJ.DiamondEdition, {

        SelectAuth: function (obj) {

            var authId = $(obj).attr("Id");
            $("#ButtonForm #BindValue").val(authId);

            Button.Dialog_SelectAuthListObj.close();
            $.L.msgSuccess("绑定认证成功");
        },
        Ajax_GetAuthlListByEID: function () {

            $.L.ajaxHandle({
                url: ACTION_URL("GetAuthListByEID", "Auth"),
                success: function (result) {

                    $("#AuthList").L_bindingDataList(result);

                }
            });
        },


    })
})(jQuery);








$("#inputTypeSave").on("click", function () {
    if ($(this).parents(".rightForm").find("input[name='FWCode']").eq(0).is(":checked")) {
        var inputType = "FwCode"  //单防伪
    } else {
        var inputType = "ALLCode" //溯源+防伪
    }

    inputTypeSave(inputType)
})




function inputTypeSave(inputType) {

    $.ajax({
        url: "/AntiFake/UpdateinputType",
        type: "POST",
        dataType: "json",
        data: { inputType: inputType },
        success: function (result) {

            if (result > 0) {
                $.L.msgSuccess("操作成功");
                //关闭右侧编辑框
            } else {
                alert("保存失败,请联系管理员");
            }
        }
    });
};









var page = [];

$.extend(page, {


    BindTitle:function(){
        var title = $("#Title").val();


    
    },


    BindBackGround: function () {

        var bg = $("#BackgroundSrcInp").val();

        if (bg != "") {
            $("#phone").css("background-image", "url('" + bg + "')")

            var $li = $(
                   '<div class="img-thumbnail">' +
                   '<img alt="null" src=" ' + bg + '" />' +
                   '</div>'
               ),
               $img = $li.find('img');

            $('#thelist').prepend($li);

       
            $('#thelist > .img-thumbnail').eq(0).mouseenter(function () {
                var url = bg;
                $(this).attr('name', url).find('img').attr('src', "/Content/webImgs/upLogo/cp_img_sc.png");
            }).mouseleave(function () {
                var url = $(this).attr('name');
                $(this).find('img').attr('src', url);
            }).click(function () {
                $("#phone").css("background-image", "none")
                BackgroundSrc = "";
                $(this).remove();
                $('#backgroundImg').css('display', 'inline-block');
            });
            $('#backgroundImg').css('display', 'none');

        }

       
    },

    BindDragImg: function () {
    
        var PicShowType = $("#PicShowType").val();
        var DragImgSrc = $("#DragImgSrc").attr("data-src");

        $("input[name='swiperShow'][value=" + PicShowType + "]").attr("checked", true);


        if (DragImgSrc != "") {
            $("#DragImgSrc").attr("src", DragImgSrc)
           
            var $li = $(
                '<div  class="img-thumbnail">' +
                    '<img alt="null" />' +
                '</div>'
            ),
            $img = $li.find('img');
            $('#DragImg_Web').prepend($li);

            $('#DragImg_Web > .img-thumbnail').eq(0).mouseenter(function () {
                var url = $(this).find('img').attr('src');
                $(this).attr('name', url).find('img').attr('src', "/Content/webImgs/upLogo/cp_img_sc.png");
            }).mouseleave(function () {
                var url = $(this).attr('name');
                $(this).find('img').attr('src', url);
            }).click(function () {
                $("#DragImgSrc").attr("src", DragDefaultImageSrc)
                $(this).remove();
                $('#DragImgWebUp').css('display', 'inline-block');
                $('#DragImgWebUp').attr('src', DragImgSrc)
            });

            $('#DragImgWebUp').css('display', 'none');

            $img.attr('src', DragImgSrc);

            var BodyHeight = $("#red1").height()
            var BodyWidth = $("#red1").width()
            var DragImgheight = (parseFloat($("#DragImgheight").val()) * BodyHeight)/100+"px";
            var DragImgwidth = (parseFloat($("#DragImgwidth").val()) * $("#red1").width())/100 + "px";
            var DragImgtop = (parseFloat($("#DragImgtop").val()) * BodyHeight) / 100 + "px";
            var DragImgleft = (parseFloat($("#DragImgleft").val()) * $("#red1").width()) / 100 + "px";

            $("#DragImgUiBox").css({ "height": DragImgheight, "width": DragImgwidth, "top": DragImgtop, "left": DragImgleft })

            if (PicShowType == 0) {
                $("#SwpieroUpload").show();
                $("#top_img").show();
                $("#DragUpload").hide();
                $("#DragImgUiBox").hide()
            } else if (PicShowType == 1) {
                $("#SwpieroUpload").hide();
                $("#top_img").hide()
                $("#DragUpload").show();
                $("#DragImgUiBox").show();
            }
        } else {
            $("#DragImgUiBox").hide();
            $("#DragUpload").hide()
        }
    },

    // 标题保存
    TitleSave: function () {
        var title = $("#Title").val();
        var id = moduleId;
        $.ajax({
            url: "/AntiFake/UpdateTitle",
            type: "POST",
            dataType: "json",
            data: { Title: title, Id: id },
            success: function (result) {
                if (result > 0) {
                    $(".pageTitle").html(title);
                    //关闭右侧编辑框
                    $("#AntiFakeTitle").hide();
                    $.L.msgSuccess("操作成功");
                } else {
                    alert("保存失败,请联系管理员");
                }
            }
        });
    },

    // 组图保存
    LunBoTuSave: function () {

       
        var Id = moduleId;
        var TimeOptions = $("#TimeOptions").val();
        var List = $("#LbtList .uploadImg");
        var array = [];
        $.each(List, function (item) {
            array[item] = List[item].currentSrc;
        });
        var PicShowType = $("input[name='swiperShow']:checked").val();
        var dragModel = page.GetDragModelFromPage();
        var GroupImg = function () {
            this.DragModel = dragModel;
            this.TimeOptions = TimeOptions;
            this.ImgListJson = JSON.stringify(array);
            this.PicShowType = PicShowType;
            this.Id = Id;
        }
        var groupImg = new GroupImg();
        $.ajax({
            url: "/AntiFake/DragAndCarouselFigureSave",
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            //data: { dragModel: dragModel, TimeOptions: TimeOptions, imgListJson: JSON.stringify(array), picShowType: PicShowType, Id: Id },
            //data: { model: groupImg },
            data: "{\"model\":" + JSON.stringify(groupImg) + "}",
            success: function (result) {
                if (result > 0) {
                    $.L.msgSuccess("操作成功");
                    $("#AntiFakeSwiper").hide();
                } else {
                    $.L.msgSuccess("操作失败，请检查网络是否异常");
                }
            }
        });
    },

    // 背景图保存
    BackGroundImgSave: function () {
        var bg = $("#BackgroundImg").val();
        var Id = moduleId;
        $.ajax({
            url: "/AntiFake/UpdateBackGroundImg",
            type: "POST",
            dataType: "json",
            data: { Bimg: bg, Id: Id },
            success: function (result) {
                if (result > 0) {
                    $.L.msgSuccess("操作成功");
                    $("#AntiFakeBackground").hide();
                    $("#phone").css("background-image", "url('" + bg + "')");
                } else {
                    alert("保存失败,请联系管理员");
                }
            }
        });
    },

    GetDragModelFromPage: function () {

        var DragModel = function () {
            this.DragImgheight = 0;
            this.DragImgwidth = 0;
            this.DragImgtop = 0;
            this.DragImgleft = 0;
            this.DragImgSrc = "";
        }
        var dragModel = new DragModel()
        var BodyHeight = $("#red1").height()
        var BodyWidth = $("#red1").width()
        var DragImgWidth = $("#DragImgUiBox").width()
        var DragImgHeight = $("#DragImgUiBox").height()
        var DragImgLeft = parseFloat($("#DragImgUiBox").css("left"))
        var DragImgTop = parseFloat($("#DragImgUiBox").css("top"))

        dragModel.DragImgheight = (DragImgHeight / BodyHeight * 100).toFixed(2) + "%";
        dragModel.DragImgwidth = (DragImgWidth / BodyWidth * 100).toFixed(2) + "%";
        dragModel.DragImgtop = (DragImgTop / BodyHeight * 100).toFixed(2) + "%";
        dragModel.DragImgleft = (DragImgLeft / BodyWidth * 100).toFixed(2) + "%";
        dragModel.DragImgSrc = $("#DragImgSrc").attr("src");

        return dragModel;

    },

    RichTextSave: function () {

        var MainContent = ue.getContent();
        var Id=moduleId

        $.ajax({
            url: "/AntiFake/RichTextSave",
            type: "POST",
            dataType: "json",
            data:{MainContent:MainContent,Id:Id},
            success: function (data) {

                if (data > 0) {
                    $.L.msgSuccess("操作成功");
                    $("#RichText").html(ue.getContent())

                    $("#RichTextRight").hide();
                }

            }

        });
    },

    BindRichText: function () {
        var mainContent = $("#MainContent").val();
        
        $("#RichText").html(mainContent);
       
        ue.ready(function () {
            ue.setContent(mainContent);
        });





    }





})




var moduleId = 0;
var ue = UE.getEditor('editor');

$(document).ready(function () {

    page.BindTitle();

    page.BindBackGround();
    page.BindDragImg();
    page.BindRichText();

    moduleId = $("#ModuleId").val();
    Button.GetList(moduleId);
    CarouselFigure.BindList();

});




$("[name='swiperShow']").change(function () {
    if ($(this).val() == 0) {
        $("#SwpieroUpload").show();
        $("#top_img").show();
        $("#DragUpload").hide();
        $("#DragImgUiBox").hide()
    } else {
        $("#SwpieroUpload").hide();
        $("#top_img").hide()
        $("#DragUpload").show();
        $("#DragImgUiBox").show();
    }
})

//富文本框配置


//选区发生改变
ue.addListener('selectionchange', function (editor) {
    $("#RichText").html(ue.getContent())
})